import React from 'react'
import ReactDOM from 'react-dom/client'

import './styles/base.css'
import './styles/index.css'

import TodoHeader from './components/TodoHeader'
import TodoMain from './components/TodoMain'
import TodoFooter from './components/TodoFooter'

class App extends React.Component {
  state = {
    itemList:[{id:'1',content:'抽烟',finish:false},
    {id:'2',content:'喝酒',finish:true},
    {id:'3',content:'烫头',finish:false}],
    // 三种状态 all active completed 默认 all
    type:'all'
  }
  render() {
    return (
      <div>
        <section className="todoapp">
          <TodoHeader cgAddItemById={this.cgAddItemById}></TodoHeader>
          <TodoMain 
            itemList={this.state.itemList} 
            type={this.state.type} 
            cgFinishById={this.cgFinishById} 
            delitemById={this.delitemById} 
            cgItemById={this.cgItemById}
            cgAllInByState={this.cgAllInByState}
          ></TodoMain>
          {this.state.itemList.length === 0 ? null : 
          <TodoFooter 
            itemList={this.state.itemList} 
            type={this.state.type} 
            clearItemByState={this.clearItemByState}
            cgListByType={this.cgListByType}
          ></TodoFooter>}
        </section>
      </div>
    )
  }

  // 方法
  cgAddItemById = (content) => {
    this.setState({
      itemList:[
        {id:Date.now(),content,finish:false},
        ...this.state.itemList
      ]
    })
  }

  cgFinishById = (id) => {
    this.setState({
      itemList : this.state.itemList.map((item) => {
        if(item.id === id) {
          return {
            ...item,
            finish: !item.finish
          }
        } else {
          return item
        }
      })
    })
  }

  delitemById = (id) => {
    this.setState({
      itemList : this.state.itemList.filter(item => item.id !== id)
    })
  }

  cgItemById = (id,content) => {
    this.setState({
      itemList : this.state.itemList.map((item) => {
        if(item.id === id) {
          return {
            ...item,
            content
          }
        } else {
          return item
        }

      })
    })
  }

  clearItemByState = () => {
    this.setState({
      itemList:this.state.itemList.filter((item) => item.finish !== true)
    })
  }

  cgListByType = (type) => {
    this.setState({
      type
    })
  }

  cgAllInByState = (stateInfo) => {
    this.setState({
      itemList : this.state.itemList.map(item => {
        return {
          ...item,
          finish:stateInfo
        }
      })
    })
  }

  componentDidMount() {
    this.setState({
      itemList:JSON.parse(localStorage.getItem('todoitem')) || []
    })
  }

  componentDidUpdate() {
    localStorage.setItem('todoitem',JSON.stringify(this.state.itemList))
  }
}

const root = ReactDOM.createRoot(document.getElementById('root'))
root.render(<App></App>)
